package com.ecar.api.aop;

import com.ecar.common.annotation.ResponseFilter;
import com.ecar.common.dto.DataBean;
import com.ecar.common.util.DataValidateUtil;
import com.ecar.common.util.JSONUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 接口返回处理aop
 * Created by admin
 */
@Component
@Aspect
public class ResponseFilterAspect {

	private static Logger log = LoggerFactory.getLogger(ResponseFilterAspect.class);

	/**
	 * 切入点，带有ResponseFilter注解的方法
	 */
	@Pointcut("@annotation(com.ecar.common.annotation.ResponseFilter)")
	public void response() {
	}

	/**
	 * 根据ResponseFilter的参数进行返回值过滤
	 * @param jp
	 * @param dataBean
	 * @return
	 * @throws Throwable
	 */
	@AfterReturning(pointcut = "response()", returning = "dataBean")
	public Object doAround(JoinPoint jp, DataBean dataBean) throws Throwable {
		if (dataBean.getCode() != 200) return dataBean;

		MethodSignature signature = (MethodSignature) jp.getSignature();
		Method method = signature.getMethod();
		ResponseFilter annotation = method.getAnnotation(ResponseFilter.class);

		Class target = annotation.target();
		String[] fields = annotation.fields();
		boolean bInclude = annotation.include();
		Object result = dataBean.getResult();
		DataValidateUtil.parseNull(result);

		String value = bInclude ? JSONUtil.serializeInclude(result, fields)
			: JSONUtil.serializeExclude(result, fields);
		if (result instanceof List) {
//			JSONArray ja = JSONArray.fromObject(value);
//			dataBean.setResult(JSONArray.toCollection(ja, target));
			dataBean.setResult(JSONArray.fromObject(value));
		} else {
			dataBean.setResult(JSONObject.fromObject(value));
		}
		return dataBean;
	}
}
